<template>
  <div class="p-2" style="height: 100%;">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover" class="table-container" style="height: calc(100% - 90px);">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:menu:add']" type="primary" plain icon="Plus" @click="openAdd()">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <div style="width: 100%; height: calc(100% - 60px);">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              ref="menuTableRef"
              v-model:expanded-row-keys="expandedRowKeys"
              v-loading="loading"
              :columns="columns"
              :data="menuList"
              :row-key="'menuId'"
              :width="width"
              :height="height"
              :expand-column-key="'menuName'"
              fixed
              @row-expand="onRowExpanded"
              @expanded-rows-change="onExpandedRowsChange"
            />
          </template>
        </el-auto-resizer>
      </div>
    </el-card>

    <!--  新增  -->
    <el-dialog v-model="dialog.shouAdd" :title="dialog.title" destroy-on-close append-to-bod width="750px">
      <Add :selectedMenu="selectedRow" @close="dialog.shouAdd = false" @success="getList" />
    </el-dialog>

    <!--  修改  -->
    <el-dialog v-model="dialog.showUpdate" :title="dialog.title" destroy-on-close append-to-bod width="750px">
      <Update :selectedMenu="selectedRow" @close="dialog.showUpdate = false" @success="getList"/>
    </el-dialog>
  </div>
</template>

<script setup  lang="tsx">
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from '@/api/system/menu';
import { MenuForm, MenuQuery, MenuVO } from '@/api/system/menu/types';
import DictTag from '@/components/DictTag/index.vue';
import Add from './components/Add.vue';
import Update from './components/Update.vue';
import { ElTableV2, ElButton, type ExpandedRowsChangeHandler, type RowExpandHandler, TableV2FixedDir } from 'element-plus';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_show_hide, sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_show_hide', 'sys_normal_disable'));

const showSearch = ref(true);
const isExpandAll = ref(false);

const dialog = reactive<any>({
  showAdd: false,
  showUpdate: false,
  title: ''
});

const queryFormRef = ref<ElFormInstance>();
let selectedRow = reactive<any>();

const queryParams = ref<any>({
  menuName: undefined,
  status: undefined
});

const menuTableRef = ref<ElTableInstance>();

const onRowExpanded = ({ expanded }: Parameters<RowExpandHandler>[0]) => {
  console.log('点击箭头图标展开/折叠：', expanded);
};

const onExpandedRowsChange = (expandedKeys: Parameters<ExpandedRowsChangeHandler>[0]) => {
  console.log('行展开状态改变时触发：', expandedKeys);
};

const columns:any = [
  { key: 'menuName', dataKey: 'menuName', title: '菜单名称', width: 180, fixed: TableV2FixedDir.LEFT },
  {
    key: 'icon',
    title: '图标',
    dataKey: 'icon',
    width: 80,
    align: 'center',
    cellRenderer: ({ cellData: icon }) => (<SvgIcon icon-class={icon} ></SvgIcon>)
  },
  {
    key: 'status',
    title: '状态',
    dataKey: 'status',
    width: 80,
    align: 'center',
    cellRenderer: ({ cellData: status }) => (<DictTag options={proxy?.useDict('sys_normal_disable').sys_normal_disable} value={status} ></DictTag>)
  },
  {
    key: 'orderNum',
    title: '排序号',
    dataKey: 'orderNum',
    width: 100,
    align: 'center',
    cellRenderer: ({ cellData: orderNum }) => <span>{orderNum}</span>
  },
  {
    key: 'path',
    title: '路径',
    dataKey: 'path',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: path }) => <span>{path}</span>
  },
  {
    key: 'isFrame',
    title: '是否内嵌框架',
    dataKey: 'isFrame',
    width: 120,
    align: 'center',
    cellRenderer: ({ cellData: isFrame }) => (
      <DictTag options={proxy?.useDict('sys_yes_no').sys_yes_no} value={isFrame}></DictTag>
    )
  },
  {
    key: 'isCache',
    title: '是否缓存',
    dataKey: 'isCache',
    width: 120,
    align: 'center',
    cellRenderer: ({ cellData: isCache }) => (
      <DictTag options={proxy?.useDict('sys_yes_no').sys_yes_no} value={isCache}></DictTag>
    )
  },
  {
    key: 'menuType',
    title: '菜单类型',
    dataKey: 'menuType',
    width: 150,
    align: 'center',
    cellRenderer: ({ cellData: menuType }) => <span>{menuType}</span>
  },
  {
    key: 'action',
    title: '操作',
    align: 'center',
    width: 130,
    fixed: TableV2FixedDir.RIGHT,
    cellRenderer: (row: any) => (
      <div style="display: flex; justify-content: center;">
        <ElButton style="margin: 0; min-width: 40px;" directives={[{ name: 'hasPermi', value: ['system:menu:edit'] }]} link type="primary"  onClick={() => openUpdate(row)}>修改</ElButton>
        <ElButton style="margin: 0; min-width: 40px;" directives={[{ name: 'hasPermi', value: ['system:menu:add'] }]} link type="primary" onClick= {() => openAdd(row)}>新增</ElButton>
        <ElButton style="margin: 0; min-width: 40px;" directives={[{ name: 'hasPermi', value: ['system:menu:remove'] }]} link type="primary" onClick={() => handleDelete(row)}>删除</ElButton>
      </div>
    )
  }
]

/** 查询菜单列表 */
const menuList = ref<MenuVO[]>([]);
const loading = ref(true);
const expandedRowKeys = ref<string[]>([])
const getList = async () => {
  loading.value = true;
  const res = await listMenu(queryParams.value);
  const data = proxy?.handleTree<MenuVO>(res.data, 'menuId');
  if (data) {
    menuList.value = data;
  }
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const openAdd = (row?: MenuVO) => {
  selectedRow = row?.rowData

  dialog.shouAdd = true;
  dialog.title = '添加菜单';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(menuList.value, isExpandAll.value);
};

/** 展开/折叠所有 */
const toggleExpandAll = (data: MenuVO[], status: boolean) => {
  data.forEach((item: MenuVO) => {
    menuTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) { toggleExpandAll(item.children, status); }
  });
};

/** 修改按钮操作 */
const openUpdate = async (row: MenuVO) => {
  selectedRow = row?.rowData

  dialog.showUpdate = true;
  dialog.title = '修改菜单';
};

/** 删除按钮操作 */
const handleDelete = async (row: MenuVO) => {
  const menuData = row.rowData;
  await proxy?.$modal.confirm('是否确认删除名称为"' + menuData.menuName + '"的数据项?');
  await delMenu(menuData.menuId);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
:deep(.table-container .el-card__body) {
  height: 100%;
}
</style>
